package com.tarena.servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * VerifyCode
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-2-2
 */
public class ImagServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 在内存中生成位图
		BufferedImage image = new BufferedImage(70, 22,
				BufferedImage.TYPE_INT_RGB);

		// 封装了画笔操作
		Graphics g = image.getGraphics();
		Random r = new Random();
		g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
		g.fillRect(2, 2, 200, 200); // 画一个矩形,四个参数，前两个是画布的坐标，后两个是长和宽
		g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

		// 生成干扰线条。
		for (int i = 1; i < 500; i++) {
			g.setColor(new Color(r.nextInt(255), 
								 r.nextInt(255),
								 r.nextInt(255)));
			g.drawOval(r.nextInt(500), r.nextInt(500), r.nextInt(500), r
					.nextInt(550));
		}
		
		// g.setFont(new Font(null, Font.BOLD|Font.ITALIC,50));
		g.drawString(r.nextInt(500) + "", 10, 10);

		// 压缩成jpeg格式
		response.setContentType("image/jpeg");
		OutputStream os = response.getOutputStream();

		// 一边压缩，一边输出，所以要有一个输出流。想把这个文件送到哪，这个流就指到那里
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

		// 内存输出流，
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] arry = baos.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(arry);

		// 输出该图片编码
		encoder.encode(image);
	}

}
